package pers.qianyu.month_202103.date_20210305;

/**
 * 最长公共子串
 * https://www.nowcoder.com/practice/f33f5adc55f444baa0e0ca87ad8a6aac?tpId=117&tqId=37799&rp=1&ru=%2Fta%2Fjob-code-high&qru=%2Fta%2Fjob-code-high%2Fquestion-ranking&tab=answerKey
 * -本题需要注意和“最长公共子序列”区别开来
 *
 * @author mizzle rain
 * @date 2021-03-05 23:23
 */
public class LCS {
    /**
     * longest common substring
     *
     * @param str1 string字符串 the string
     * @param str2 string字符串 the string
     * @return string字符串
     */
    public String LCS(String str1, String str2) {
        int m = str1.length(), n = str2.length();
        int[][] dp = new int[m + 1][n + 1];
        // dp[i][j] 表示的是以 str1[i]、str2[j] 结尾的最长公共子串，如果str1[i] != str2[j] 就为 0
        int end = 1, len = 0;
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                    if (len <= dp[i][j]) {
                        len = dp[i][j];
                        end = i;
                    }
                }
            }
        }
        return str1.substring(end - len, end);
    }
}